<template>
  <!-- <basic-container></basic-container> -->
  <div class="gather-content">
    <div class="gather-content-left">
      <div class="gather-content-left-top">
        {{ route.query.clinicalCaseType == '8' ? '纳排CRF--' : '数据采集--' }}
        <el-button type="success" plain :icon="Back" @click="handleBack">返回业务</el-button>
      </div>
      <div class="gather-content-left-tree">
        <el-collapse
          accordion
          v-model="activeName"
          class="flow-text-content"
          v-if="route.query.clinicalCaseType == '8'"
        >
          <el-collapse-item :name="index" v-for="(item, index) in crfTree" :key="index">
            <template #title>
              <div class="lord-content">
                <Fold style="width: 16px; height: 16px; margin-right: 5px" />
                <span>{{ item.title }}</span>
              </div>
            </template>
            <div
              class="seed-content"
              v-for="(v, i) in item.npOrOtherCrfList"
              :key="i"
              style="color: #fff"
              :style="crfClickVal.crf === v.crf ? 'color:yellow' : 'color: #fff'"
              @click="handleCrf(v, i)"
            >
              <Document style="width: 16px; height: 16px; margin-right: 5px" />
              <span>{{ v.crfName }}</span>
            </div>
          </el-collapse-item>
        </el-collapse>

        <!-- 外层折叠面板 -->
        <el-collapse
          accordion
          v-model="activeParent"
          v-else
          class="flow-text-content flow-text-content1"
        >
          <el-collapse-item v-for="(item, index) in crfTree" :key="index" :name="index">
            <template #title>
              <div class="lord-content">
                <Fold style="width: 16px; height: 16px; margin-right: 5px" />
                <span>{{ item.title }}</span>
              </div>
            </template>

            <!-- 内层嵌套折叠面板 -->
            <el-collapse accordion v-model="activeChild" class="nested-collapse">
              <el-collapse-item v-for="(v, i) in item.children" :key="i" :name="`${index}-${i}`">
                <template #title>
                  <div class="lord-content">
                    <Fold style="width: 16px; height: 16px; margin-right: 5px" />
                    <span>{{ v.title }}</span>
                  </div>
                </template>

                <!-- 子项内容 -->
                <div
                  class="seed-content"
                  v-for="(vv, ii) in v.crfList"
                  :key="ii"
                  :style="{
                    color: crfClickVal.crf === vv.crf ? 'yellow' : '#fff',
                  }"
                  @click="handleCrf(vv, ii, i)"
                >
                  <Document style="width: 16px; height: 16px; margin-right: 5px" />
                  <span>{{ vv.crfName }}</span>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <div class="gather-content-right">
      <basic-container class="gather-basic-container">
        <div class="gather-content-right-top">
          <div class="gather-content-right-title">入组采集</div>
          <div class="gather-content-right-hint">
            <div class="gather-content-right-hint-text">
              <!-- <div style="display: flex; flex: 1">
                <span style="color: red">注：</span>
                <span class="hint-text">
                  <Fold class="hint-icon" />
                  代表分组，
                </span>
                <span class="hint-text">
                  <Message class="hint-icon" />
                  代表CRF未采集，
                </span>
                <span class="hint-text">
                  <Clock class="hint-icon" />
                  代表CRF采集中，
                </span>
                <span class="hint-text">
                  <CircleCheckFilled class="hint-icon" style="color: #3c763d" />
                  代表已采集完CRF，
                </span>
                <span class="hint-text">
                  <WarnTriangleFilled class="hint-icon" style="color: #f39c12" />
                  代表CRF不可采集（质疑中），
                </span>
                <span class="hint-text">
                  <Grid class="hint-icon" />
                  代表质疑完成。
                </span>
              </div> -->
              <div class="gather-content-right-hint-btn">
<!--                <el-button type="warning" plain :icon="FolderOpened" @click="handleMenu(1)"
                  >文件管理</el-button
                >
                <el-button type="success" plain :icon="FolderChecked" @click="handleMenu(2)"
                  >导出CRF</el-button
                >-->
                <el-button type="warning" plain :icon="Refresh" @click="handleMenu(3)"
                  >清空</el-button
                >
              </div>
            </div>
            <div class="gather-content-right-type">
              <div class="type-text">
                <!-- <span style="color: red; margin-right: 10px">本表状态：采集中</span> -->
                <span>病例姓名：{{ clinicalCaseValue.name }}</span>
              </div>
              <el-row :gutter="20" style="padding-left: 58px">
                <!-- <el-col :span="24" style="display: flex">
                  <span style="line-height: 32px">日志记录</span>
                  <el-col :span="18">
                    <el-select v-model="value" placeholder="请选择日志记录">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-col>
                </el-col> -->
                <el-col :span="24" style="display: flex">
                  <span style="line-height: 32px">化验单照片</span>
                  <el-col :span="6">
                    <el-select v-model="NPValue" filterable placeholder="请选择化验单照片">
                      <el-option
                        v-for="item in NPOptions"
                        :key="item.dictKey"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="12">
                    <el-input v-model="uploadInput" placeholder="未选中文件" style="height: 34px">
                      <template #prepend
                        ><el-upload
                          v-model:file-list="fileList"
                          class="upload-demo"
                          action="/api/blade-resource/oss/endpoint/put-file"
                          multiple
                          :show-file-list="false"
                          :on-preview="handlePreview"
                          :on-remove="handleRemove"
                          :on-success="handleSuccess"
                          :before-remove="beforeRemove"
                          :before-upload="beforeUpload"
                          :limit="3"
                          :on-exceed="handleExceed"
                          :with-credentials="true"
                          :headers="headers"
                        >
                          <el-button type="primary">选择文件</el-button>
                        </el-upload></template
                      >
                    </el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="success" plain :icon="FolderChecked">上传</el-button>
                  </el-col>
                </el-col>
              </el-row>
              <!-- <div class="crf-name">移植后+360天+-7天</div> -->
            </div>
          </div>
        </div>
        <div class="gather-content-right-main" v-if="crfTree.length != 0">
          <!-- @formChange="onFormDataChange" -->
          <VFormRender
            :form-json="formJson"
            :form-data="formData"
            :option-data="optionData"
            ref="vFormRef"
          >
          </VFormRender>
          <div style="display: flex; justify-content: center; margin-top: 10px">
            <!-- <el-button type="primary" plain :icon="Back" @click="handleBringIntoMenu(0)"
              >暂 存</el-button
            > -->
            <el-button type="primary" plain :icon="Check" @click="handleSubmit">提 交</el-button>
          </div>
        </div>
      </basic-container>
    </div>
  </div>
</template>
<script setup>
import { collectInfoSubmit, clinicalCaseDetail } from '@/api/trial/trial';
import { npCrf, groupAcquisition } from '@/api/clinicalcase/clinicalCase';
import { dictionary } from '@/api/crf/crf';
import { getDetail } from '@/api/crf/crf.js';
import { Base64 } from 'js-base64';
import website from '@/config/website';
import { getToken } from '@/utils/auth';
import { Back, FolderOpened, FolderChecked, Refresh, Check } from '@element-plus/icons-vue';
import VFormRender from '@/components/form-render/index.vue';
import { ref, reactive, computed, onMounted, defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
const crud = ref();
const route = useRoute();
const emit = defineEmits();
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const store = useStore();
const formJson = ref({});
const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});
let activeName = ref(0);
let crfClickVal = ref({
  phaseIndex: 0,
});
let activeParent = ref(0);
let activeChild = ref('0-0');
let clinicalCaseValue = ref({});
let crfClickIndex = ref(0);

let NPValue = ref('');
let NPOptions = ref([]);

const headers = ref({
  Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
  'Blade-Requested-With': 'BladeHttpRequest',
});

onMounted(() => {
  if (routerQuery.value.clinicalCaseId) {
    clinicalCaseDetail(routerQuery.value.clinicalCaseId).then(res => {
      clinicalCaseValue.value = res.data.data;
    });
  }
  initData();
});
const crfTree = ref([]);

const initData = () => {
  if (routerQuery.value.clinicalCaseType == '8') {
    npCrf(routerQuery.value.groupId, routerQuery.value.clinicalCaseId).then(res => {
      const DATA = res.data.data;
      crfTree.value = res.data.data;
      crfClickVal.value = DATA[0].npOrOtherCrfList[crfClickIndex.value];
      if (crfClickVal.value.content) {
        formData.value = JSON.parse(crfClickVal.value.content);
      }
      getDetailData(DATA[0].npOrOtherCrfList[crfClickIndex.value].crf);
    });
  } else {
    groupAcquisition(routerQuery.value.groupId, routerQuery.value.clinicalCaseId).then(res => {
      const DATA = res.data.data;
      // crfTree.value = res.data.data[0].children;
      crfTree.value = res.data.data;
      if (crfClickVal.value.phaseIndex === 0) {
        crfClickVal.value =
          DATA[0].children[crfClickVal.value.phaseIndex || 0].crfList[crfClickIndex.value];
      }
      if (crfClickVal.value.content) {
        formData.value = JSON.parse(crfClickVal.value.content);
      }
      getDetailData(
        DATA[0].children[crfClickVal.value.phaseIndex || 0].crfList[crfClickIndex.value].crf
      );
    });
  }
  initDictionary();
};
// 字典接口方法
const initDictionary = () => {
  dictionary('crf_collect_files').then(res => {
    NPOptions.value = res.data.data;
  });
};
const getDetailData = async crfId => {
  const { data: res } = await getDetail(crfId);
  if (res.code == 200) {
    formJson.value = JSON.parse(res.data.content);
    vFormRef.value.setFormJson(formJson.value);
  }
};
let uploadInput = ref('');
const handleSubmit = () => {
  // 获取所填数据对象
  vFormRef.value.getFormData().then(res => {
    let crfVal = crfClickVal.value;
    console.log('提交按钮', crfVal);
    let form = {
      content: JSON.stringify(res),
      trial: routerQuery.value.trialId,
      groupId: crfVal.groupId || routerQuery.value.groupId,
      phaseId:
        routerQuery.value.clinicalCaseType == '8'
          ? null
          : crfTree.value[0].children[crfClickVal.value.phaseIndex || 0].id,
      crfId: crfVal.crf,
      caseUserId: routerQuery.value.clinicalCaseId,
      linkId: crfVal.id,
      type: routerQuery.value.clinicalCaseType == '8' ? '1' : '2',
      id: crfVal.collectInfoId || null,
    };
    console.log(form);
    collectInfoSubmit(form).then(res => {
      ElMessage.success('提交成功！');
      initData();
    });
  });
};

const handleCrf = (childrenVal, index, phaseIndex = null) => {
  console.log('点击点击', childrenVal.content);
  if (childrenVal.content != '') {
    formData.value = JSON.parse(childrenVal.content);
  }
  crfClickVal.value = childrenVal;
  if (phaseIndex != null) {
    crfClickVal.value.phaseIndex = phaseIndex;
  }
  crfClickIndex.value = index;
  getDetailData(childrenVal.crf);
};
// 按钮点击事件
/*
  type 1：文件管理
  type 2：导出CRF
  type 3：清空
*/
const handleMenu = type => {
  const actions = {
    3: () => {
      vFormRef.value.resetForm();
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};
// 上传图片之前钩子
const beforeUpload = () => {
  headers.value[website.tokenHeader] = 'bearer ' + getToken();
};
// 响应式变量：用于存储文件列表
const fileList = ref([]);
// 上传成功钩子
const handleSuccess = (response, file, fileList) => {
  console.log('上传成功', response, file, fileList);
  uploadInput.value = fileList.map(ele => ele.name).join(',');
};
// 方法：处理预览文件
const handlePreview = file => {
  console.log('预览文件', file, fileList.value);
  // 这里可以加入跳转或打开文件的操作，例如预览图片等
};

// 方法：处理删除文件
const handleRemove = (file, fileList) => {
  console.log('删除文件', file);
  console.log('更新后的文件列表', fileList);
  // 这里可以加上删除文件的额外操作，例如提示用户删除等
};

// 方法：在删除文件之前进行确认
const beforeRemove = (file, fileList) => {
  return new Promise((resolve, reject) => {
    // 在这里可以弹出一个确认框或者其他操作
    const confirmed = window.confirm(`确定要删除文件 ${file.name} 吗？`);
    if (confirmed) {
      resolve(); // 确认删除
    } else {
      reject(); // 取消删除
    }
  });
};

// 方法：文件超出限制时的处理
const handleExceed = (files, fileList) => {
  alert(`上传文件数量超过限制，当前选择了 ${files.length} 个文件，最大允许上传 3 个文件`);
};

const handleBack = () => {
  let selectTab = route.query.clinicalCaseType == '8' ? 4 : 5;
  router.push({
    path: '/trial/menu',
    query: {
      selectTab: selectTab,
      trialId: routerQuery.value.trialId,
    },
  });
};
</script>
<style scoped lang="scss">
.gather-content {
  width: 100%;
  height: 100%;
  display: flex;
}
.gather-content-left {
  width: 230px;
  height: 100%;
  background-color: #09053a;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.gather-content-left-top {
  width: 100%;
  height: 50px;
  color: #fff;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  margin-top: 5px;
}
.gather-content-left-tree {
  width: 100%;
  height: calc(100% - 70px);
  overflow-y: auto;
  ::v-deep .el-tree {
    background-color: #1e3243;
  }
  ::v-deep .is-focusable {
    color: #fff;
  }
  ::v-deep .el-tree-node__content {
    background-color: #f5f7fa00 !important;
  }
  ::v-deep .el-tree-node__content:hover {
    background-color: #f5f7fa00 !important;
  }
}
::v-deep .highlighted {
  color: #ffd700 !important; /* 改变颜色 */
}
::v-deep .blue-node {
  color: blue !important; /* 改变颜色 */
}
.flow-text-content {
  ::v-deep .el-collapse-item__content {
    padding-bottom: 0;
  }
}
.nested-collapse {
  padding-left: 20px;
  border: none;
}
.gather-content-right {
  width: calc(100% - 230px);
  height: 100%;
}
.gather-content-right-top {
  width: 100%;
  // height: 250px;
  height: 190px;
  margin-bottom: 10px;
  border-bottom: 1px solid #f0f2f5;
}
.gather-content-right-title {
  width: 100%;
  height: 30px;
  line-height: 30px;
  color: black;
  font-size: 20px;
  font-weight: 550;
}
.gather-content-right-hint {
  width: 100%;
  // height: 200px;
  height: 170px;
}
.gather-content-right-hint-text {
  width: 100%;
  height: auto;
  color: black;
  // font-size: 14px;
  display: flex;
  align-items: center;
}
.hint-text {
  display: flex;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.hint-icon {
  width: 16px;
  height: 16px;
}
.gather-content-right-hint-btn {
  width: auto;
  height: 100%;
}
.gather-content-right-type {
  width: 100%;
  height: auto;
  margin-top: 10px;
  ::v-deep .upload-demo {
    display: flex;
  }
}
.type-text {
  color: black;
  margin-bottom: 10px;
}
.crf-name {
  width: 100%;
  height: auto;
  text-align: center;
  color: #397db8;
  font-size: 30px;
}
.gather-basic-container {
  height: 99%;
  font-size: 14px;
  ::v-deep .el-card,
  ::v-deep .el-card__body {
    height: 100%;
  }
}
.gather-content-right-main {
  width: 100%;
  // height: calc(100% - 300px);
  height: calc(100% - 240px);
  overflow-y: auto;
  overflow-x: hidden;
}
.flow-text-content {
  width: 100%;
  height: auto;
  border: none;
  ::v-deep .el-collapse-item__header,
  ::v-deep .el-collapse-item__wrap {
    background-color: #1e3243;
    border: none;
    // height: 40px;
    color: #fff;
    cursor: pointer;
  }
}
.lord-content {
  height: 35px;
  color: #fff;
  // padding: 5px 10px;
  font-size: 14px;
  display: flex;
  align-items: center;
}
.seed-content {
  color: #afbdb4;
  padding: 5px 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
}
</style>
